package com.gitee.fsadmin.service.sys;

import com.gitee.fsadmin.common.enums.ConfigKeyEnum;
import com.gitee.fsadmin.common.util.BCrypt;
import com.gitee.fsadmin.common.util.PasswordUtil;
import com.gitee.fsadmin.dao.entity.SysUser;
import com.gitee.fsadmin.dao.mapper.UpgradeMapper;
import com.gitee.fsadmin.service.sys.login.enums.RegTypeEnum;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.solon.annotation.Db;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Component;


/**
 * @author 六如
 */
@Component
public class UpgradeService {

    @Inject
    private SysConfigService sysConfigService;

    @Inject
    private SysUserService sysUserService;

    @Db
    private UpgradeMapper upgradeMapper;

    @Init
    public void init() {
        this.initJwtSecret();
        this.insertAdmin();
    }

    private void initJwtSecret() {
        String configKey = ConfigKeyEnum.JWT_SECRET.getKey();
        String value = sysConfigService.getRawValue(configKey);
        if (StringUtils.isBlank(value)) {
            value = PasswordUtil.getRandomSimplePassword(30);
            sysConfigService.setConfig(configKey, value);
        }
    }


    public void insertAdmin() {
        SysUser userInfo = sysUserService.getByUsername("admin");
        if (userInfo != null) {
            return;
        }
        String username = "admin";
        String tpl = "INSERT INTO `sys_user` (`id`, `username`, `password`, `nickname`, `reg_type`) VALUES \n" +
                "\t(%s, '%s','%s','%s','%s');";
        // 初始密码
        String defPassword = "123456";
        defPassword = DigestUtils.sha256Hex(defPassword);
        String encodedPassword = BCrypt.hashpw(defPassword, BCrypt.gensalt());
        Long userId = 1L;
        String sql = String.format(tpl, userId, username, encodedPassword, username, RegTypeEnum.BACKEND.getValue());
        runSql(sql);
    }

    protected void runSql(String sql) {
        upgradeMapper.runSql(sql);
    }

}
